var gulp = require('gulp'); //gulp库
var webpack = require("webpack"); //webpack库
var sass = require('gulp-sass'); //处理sass
var postcss = require('gulp-postcss'); //自动添加css前缀
var minifycss = require('gulp-minify-css'); //压缩css
//var uglify=require('gulp-uglify');//压缩js
var fs = require('fs'); //文件
var plumber = require('gulp-plumber'); //处理gulp错误，避免gulp进程挂掉
var watch = require('gulp-watch'); //监听新建
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
const VueLoaderPlugin = require('vue-loader/lib/plugin')



var src = "src"; //开发目录
var dist = "dist"; //生成目录
var publicPath = "."; //路径








/*------------------sass预编译----------------*/
gulp.task('sass', () => {
	return watch(src + "/sass/*.scss", function() {
		gulp.src([src + '/sass/*.scss'])
			.pipe(plumber())
			.pipe(sass())
			.pipe(postcss())
			.pipe(minifycss())
			.pipe(gulp.dest(dist + '/css'))
			.pipe(reload({
				stream: true
			}));
		console.log("[" + new Date().toLocaleTimeString() + "]", 'Finished', 'css')

	});
});


/*------------------vue预编译----------------*/
gulp.task('vue', function() {
	return watch(src + "/*.vue", function(res) {
		var filename = res.history[0].split('\\')
		createjs({
			path: filename[filename.length - 1]
		});
	});
});

/*------------------拷贝图片----------------*/
gulp.task('copyimg', function() {
	return watch([src + '/img/**/*.*'], function() {
		gulp.src([src + '/img/**/*.*']).pipe(gulp.dest(dist + '/img/'));
	})
});

/*------------------拷贝字体----------------*/
gulp.task('copyfont', function() {
	return watch([src + '/font/**/*.*'], function() {
		gulp.src([src + '/font/**/*.*']).pipe(gulp.dest(dist + '/font/'));
	})
});

/*------------------拷贝公共js----------------*/
gulp.task('copyjs', function() {
	return watch([src + '/commonjs/*.*'], function(res) {
		console.log("[" + new Date().toLocaleTimeString() + "]", 'Finished', 'js')
		gulp.src([src + '/commonjs/*.*']).pipe(gulp.dest(dist + '/js/'));
	})
});

/*------------------自动刷新浏览器----------------*/
gulp.watch([dist + '/**/*.html']).on('change', reload);
gulp.watch([src + '/component/*.vue'], function() {
	createjs();
})


/*------------------webpack处理js-------------------*/
function createjs(res) {
	let filename = "",
		entryList = [];
	if (res) {
		filename = res.path.split('\\');
		filename = filename[filename.length - 1];
	}

	if (res && filename.indexOf('.vue') > -1) {
		entryList.push(filename);
	} else {
		let tmpList = fs.readdirSync(src);
		tmpList.forEach((v) => {
			if (v.indexOf('.vue') > -1) {
				entryList.push(v);
			}
		})
	}

	entryList.forEach((v) => {
		webpack(webpackConfig(v), function(error, stats) {
			if (!error && !stats.hasErrors()) {
				createHTML(v);
				console.log("[" + new Date().toLocaleTimeString() + "]", 'Finished', v);
			} else {
				console.log("[" + new Date().toLocaleTimeString() + "]", "Error", v, error, stats.compilation.errors);
			}
		});
	});
}

function webpackConfig(filename) {
	let config = {
		entry: __dirname + "/main.js",
		output: {
			path: __dirname + '/' + dist + "/js/",
			filename: filename.split('.')[0] + ".js"
		},
		/* optimization:{
			minimizer: true,
		}, */
		module: {
			rules: [{
					test: /(\.vue)$/,
					loader: 'vue-loader',
					options: {
						extractCSS: true
					}
				},
				{
					test: /(\.js)$/,
					loader: 'babel-loader',
					options: {
						presets: ["@babel/react", "@babel/env"]
					}
				},
				// 它会应用到普通的 `.css` 文件
			    // 以及 `.vue` 文件中的 `<style>` 块
				{
					test: /\.css$/,
					loader: [
						'vue-style-loader',
						'css-loader'
					]
				}
			]
		},
		plugins: [
			new VueLoaderPlugin(),// 请确保引入这个插件！
			new webpack.DefinePlugin({
				'VUECOMPONENT': JSON.stringify('./' + src + '/' + filename)
			})
		]
	};
	return config;
}

function createHTML(filename) {
	filename = filename.substr(0, filename.length - 3);
	var version = 'v=' + new Date().getTime();
	var file = fs.openSync(dist + "/" + filename + 'html', 'w');
	var config = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf-8').replace(/\r\n| /g, ''));
	var cssStr = "",
		scriptStr = ['', '', ''];
	for (var i = 0; i < config.css.length; i++) {
		cssStr += '<link rel="stylesheet" href="' + config.css[i] + '.css?' + version + '"/>';
	}
	if (config.js) {
		if (config.js.head) {
			for (i = 0; i < config.js.head.length; i++) {
				scriptStr[0] += '<script src="' + publicPath + '/js/' + config.js.head[i] + '.js?' + version + '"></script>';
			}
		}
		if (config.js.foot) {
			for (i = 0; i < config.js.foot.length; i++) {
				scriptStr[1] += '<script src="' + publicPath + '/js/' + config.js.foot[i] + '.js?' + version + '"></script>';
			}
		}
		var tmpfilename = filename.substr(0, filename.length - 1);
		if (config.js[tmpfilename]) {
			for (i = 0; i < config.js[tmpfilename].length; i++) {
				scriptStr[2] += '<script src="' + publicPath + '/js/' + config.js[tmpfilename][i] + '.js?' + version +
					'"></script>';
			}
		}
	}



	var htmlData =
		'<!DOCTYPE html>\
            <html lang="en">\
            <head>\
                <meta name="renderer" content="webkit">\
                <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no,minimal-ui"/>\
				<meta name="apple-mobile-web-app-capable" content="yes" />\
				<meta name="screen-orientation" content="portrait">\
				<meta name="x5-orientation" content="portrait">\
				<meta name="full-screen" content="yes">\
				<meta name="x5-fullscreen" content="true">\
                <meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge">\
                <meta charset="UTF-8">\
                ' +
		cssStr + '\
                ' + scriptStr[0] +
		'\
                <title>易书屋</title>\
            </head>\
            <body>\
                <div id="main"></div>\
                ' +
		scriptStr[1] + '\
                ' + scriptStr[2] + '\
                <script src="' + publicPath + '/js/' +
		filename + 'js?' + version + '"></script>\
            </body>\
            </html>';
	fs.writeFileSync(file, htmlData);
	fs.close(file);
}



/*------------------默认任务----------------*/
gulp.task('default', gulp.parallel('sass', 'vue','copyimg','copyfont','copyjs'));
browserSync.init({
    server: "./dist"
});

